import Popup from "../btoolkit/components/Popup";
import BButton from "../btoolkit/components/BButton";
import Http from "../btoolkit/network/Http";
import PopupAlert from "../btoolkit/components/PopupAlert";
import App from "../btoolkit/framework/App";
import SDKManager, { Platform } from "../btoolkit/sdk/SDKManager";
import AudioManager from "../btoolkit/AudioManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PopupWatchVideo extends Popup {

    @property(cc.Node)
    btnConfirm: cc.Node = null;

    private onWatchVideoEnded: Function;
    private thisObj: any;

    /**
     * @param onWatchVideoEnded 看完视频则返回true
     * @param thisObj 涉及三方SDK回调，thisObj不能省
     */
    static show(onWatchVideoEnded: Function, thisObj: any, dialogFrame?: string) {
        let node: cc.Node = cc.instantiate(App.instance.resPreloader.getRes('prefabs/common/PopupWatchVideo'));
        cc.Canvas.instance.node.addChild(node);
        let popup: PopupWatchVideo = node.getComponent(PopupWatchVideo);
        popup.onWatchVideoEnded = onWatchVideoEnded;
        popup.thisObj = thisObj;
        popup.onClose = () => {
            if (onWatchVideoEnded) {
                onWatchVideoEnded(false);
            }
        }
        if (dialogFrame) {
            let atlas: cc.SpriteAtlas = App.instance.resPreloader.getRes('textures/common/common');
            popup.dialog.getComponent(cc.Sprite).spriteFrame = atlas.getSpriteFrame(dialogFrame);
        }
        AudioManager.playVoice('common/voice_WatchVideoToGet');
    }

    onLoad() {
        super.onLoad();
        BButton.addButton(this.btnConfirm).setTouchUpEvent(() => {
            if (!Http.isNetworkOK) {
                PopupAlert.show('当前网络不可用');
                return;
            }

            let timestamp = new Date().getTime();
            SDKManager.instance.showRewardVideo((isEnded: boolean) => {
                this.node.destroy();
                if (SDKManager.platform != Platform.Other) {
                    this.onClose = null;
                    if (this.onWatchVideoEnded) {
                        this.onWatchVideoEnded.call(this.thisObj, isEnded);
                    }
                    if (new Date().getTime() - timestamp < 500) {
                        PopupAlert.show('操作太频繁了')
                    }
                } else {
                    //TODO:IDE环境测试
                    this.onClose = null;
                    if (this.onWatchVideoEnded) {
                        this.onWatchVideoEnded.call(this.thisObj, true);
                    }
                }
            })
        });
    }

}
